<template>
  <!-- 1数学几何计算/1三维向量Vector3/ -->
  <div @click="clickObj" id="webgl" class="main"></div>
</template>
<script setup>
import { onMounted } from "vue";
import { renderer, camera } from "./RendererCamera.js"; //渲染器对象和相机对象
import { scene } from "./scene/index.js"; //Three.js三维场景
import { baseGroup } from "./scene/mesh.js";
import * as THREE from "three";

window.onresize = function () {
  const width = window.innerWidth;
  const height = window.innerHeight;
  renderer.setSize(width, height);
  camera.aspect = width / height;
  // 渲染器执行render方法的时候会读取相机对象的投影矩阵属性projectionMatrix
  // 但是不会每渲染一帧，就通过相机的属性计算投影矩阵(节约计算资源)
  // 如果相机的一些属性发生了变化，需要执行updateProjectionMatrix ()方法更新相机的投影矩阵
  camera.updateProjectionMatrix();
};

const width = window.innerWidth;
const height = window.innerHeight;
const clickObj = (event) => {
  const px = event.offsetX;
  const py = event.offsetY;
  //屏幕坐标px、py转WebGL标准设备坐标x、y
  //width、height表示canvas画布宽高度
  const x = (px / width) * 2 - 1;
  const y = -(py / height) * 2 + 1;
  //创建一个射线投射器`Raycaster`
  const raycaster = new THREE.Raycaster();
  //.setFromCamera()计算射线投射器`Raycaster`的射线属性.ray
  // 形象点说就是在点击位置创建一条射线，射线穿过的模型代表选中
  raycaster.setFromCamera(new THREE.Vector2(x, y), camera);
  const intersects = raycaster.intersectObjects(baseGroup.children);
  if (intersects.length > 0) {
    window.open(intersects[0].object._info.herf, "_blank");
  }
};
onMounted(() => {
  document.getElementById("webgl").appendChild(renderer.domElement);
});
function render() {
  renderer.render(scene, camera); //执行渲染操作
  // model.rotation.y += 0.002;
  requestAnimationFrame(render); //请求再次执行渲染函数render，渲染下一帧
}
render();
</script>
<style scoped>
</style>